package netzwerk;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicBoolean;

public class TimeServerThread implements Runnable {

	private DatagramPacket packet;
	AtomicBoolean timeThreadActive;


	public TimeServerThread(AtomicBoolean timeThreadActive) {
		this.timeThreadActive = timeThreadActive;
	}

	@Override
	public void run() {
		try (DatagramSocket dSocket = new DatagramSocket(6667);) {
			int packetMaxSize = 4;
			String command = "time";
			byte buffer[] = null;
			buffer = command.getBytes();
			while (timeThreadActive.get()) {
				try {

					// Paket empfangen
					packet = new DatagramPacket(new byte[packetMaxSize], packetMaxSize);
					dSocket.receive(packet);

					// Absender (Client) und Paketdaten auslesen
					InetAddress address = packet.getAddress();
					int port = packet.getPort();
					int len = packet.getLength();
					byte[] data = packet.getData();
					System.out.printf("Anfrage von %s vom Port %d mit der Länge %d:%n%s%n",
					 address, port, len, new String(data, 0, len));

					// Prüfen, welchen String/welche Anfrage der Client geschickt hat
					String dataString = new String(packet.getData()); // Hier erwarten wir den String "time"

					if (dataString.equals("time")) {

						// Aktuelle Zeit ermitteln und formatieren
						Date currentTime = new Date();
						SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss");
						String dateParsed = dateFormat.format(currentTime);

						// Paket mit aktueller Zeit vorbereiten und an Client senden
						buffer = dateParsed.getBytes();
						packet = new DatagramPacket(buffer, buffer.length,
								packet.getSocketAddress());
						dSocket.send(packet);

					} else {

						buffer = new String("Command unknown").getBytes();

						// Paket mit Feedback über ungültiges Schlüsselwort vorbereiten
						packet = new DatagramPacket(buffer, buffer.length,
								packet.getSocketAddress());
						// Paket versenden
						dSocket.send(packet);
					}

				} catch (IOException e) {
					timeThreadActive.set(false);
					e.printStackTrace();
				}
			}

		} catch (SocketException e) {
			e.printStackTrace();
		}

	}
}